import { useSyncExternalStore } from "react";

export default function useHistory () {
  
  const subscribe = (callback: () => void) => {
    window.addEventListener('popstate',callback)
    window.addEventListener('hashchange',callback)
    return () => {
      window.removeEventListener('popstate',callback)
      window.removeEventListener('hashchange',callback)
    }
    // popstate只能监听前进和后退
  }

  const getSnapshot = () => {
    return window.location.href
  }

  const url = useSyncExternalStore(subscribe, getSnapshot);

  const push = (url:string) => {
    window.history.pushState({}, '', url);
    window.dispatchEvent(new PopStateEvent('popstate'))
  }

  const replace = (url:string) => {
    window.history.replaceState({}, '', url);
    window.dispatchEvent(new HashChangeEvent('hashchange'))
  }

  return [url,push,replace] as const

}